<!DOCTYPE html>
<link rel="help" href="https://github.com/WICG/WebOTP">
<title>Tests OTPCredential</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script type="module">
import {Status, expectOTPRequest} from './support/otpcredential-helper.js';

promise_test(async t => {
  await expectOTPRequest().andReturn(
      () => ({status: Status.SUCCESS, otp: "ABC"}));

  let cred = await navigator.credentials.get({otp: {transport: ["sms"]}});

  assert_equals(cred.code, "ABC");
}, 'Basic usage');

promise_test(async t => {
  await expectOTPRequest().andReturn(
      () => ({status: Status.SUCCESS, otp: "ABC"}));
  await expectOTPRequest().andReturn(
      () => ({status: Status.SUCCESS, otp: "ABC2"}));

  let sms1 = navigator.credentials.get({otp: {transport: ["sms"]}});
  let sms2 = navigator.credentials.get({otp: {transport: ["sms"]}});

  let cred2 = await sms2;
  let cred1 = await sms1;

  assert_equals(cred1.code, "ABC");
  assert_equals(cred2.code, "ABC2");
}, 'Handle multiple requests in different order.');

promise_test(async t => {
  await expectOTPRequest().andReturn(() => ({status: Status.CANCELLED}));
  await expectOTPRequest().andReturn(
      () => ({status: Status.SUCCESS, otp: "success"}));

  let cancelledRequest = navigator.credentials.get({otp: {transport: ["sms"]}});
  let successfulCred =
      await navigator.credentials.get({otp: {transport: ["sms"]}});

  assert_equals(successfulCred.code, "success");

  try {
    await cancelledRequest;
    assert_unreached('Expected AbortError to be thrown.');
  } catch (error) {
    assert_equals(error.name, "AbortError");
  }
}, 'Handle multiple requests with success and error.');

promise_test(async t => {
  await expectOTPRequest().andReturn(() => ({status: Status.CANCELLED}));

  await promise_rejects_dom(t, 'AbortError', navigator.credentials.get(
    {otp: {transport: ["sms"]}}));
}, 'Deal with cancelled requests');

promise_test(async t => {
  const controller = new AbortController();
  const signal = controller.signal;

  controller.abort();
  await promise_rejects_dom(t, 'AbortError', navigator.credentials.get(
    {otp: {transport: ["sms"]}, signal: signal}));
}, 'Should abort request');

promise_test(async t => {
  const controller = new AbortController();
  const signal = controller.signal;

  controller.abort('CustomError');
  await promise_rejects_exactly(t, 'CustomError', navigator.credentials.get(
    {otp: {transport: ["sms"]}, signal: signal}));
}, 'Should abort request with reason');
</script>
